import React, { useEffect, useState } from 'react';
import {
  Card,
  Grid,
  Space,
  Button,
  Input,
  Message,
  Typography,
  Popconfirm,
} from '@arco-design/web-react';
import { useLocation } from 'react-router-dom';
import { getHelpManualDetail } from '@/api/manuals';
import { manualsTypeOpt } from '../educationManuals/common';
import styles from '@/pages/manuals/style/manualsContent.module.less';
import {
  IconPlus,
  IconDelete,
  IconClose,
  IconPlayArrow,
  IconDragDot,
} from '@arco-design/web-react/icon';
import { guid } from '@/utils/common';
import aliOss from '@/utils/aliOss';
import { configureHelpManual } from '@/api/manuals';
import { ReactSortable } from 'react-sortablejs';

const Row = Grid.Row;
const Col = Grid.Col;

const Title = Typography.Title;

function manualsContent() {
  function useQuery() {
    return new URLSearchParams(useLocation().search);
  }
  const query = useQuery();
  const ID = query.get('ID');

  useEffect(() => {
    getDetail();
  }, []);

  const [content, setContent] = useState(null);
  const [typeLabel, setTypeLabel] = useState('');
  const [currentUplevel, setCurrentUplevel] = useState(null);
  const [currentUpIndex1, setCurrentUpIndex1] = useState(null);
  const [currentUpIndex2, setCurrentUpIndex2] = useState(null);
  const [videoIsUploading, setVideoIsUploading] = useState(false);
  const getDetail = async () => {
    const res: any = await getHelpManualDetail({ ID });
    if (res.StatusCode === 200) {
      setContent(res.Result);
      const label = manualsTypeOpt.find(
        (opt) => opt.value === res.Result.Type
      )?.label;

      setTypeLabel(label);
    } else {
      Message.error(res.Message);
      history.back();
    }
  };

  const addFirstLevel = () => {
    const addData = {
      ID: guid(),
      ConverPic: '',
      MediaUrl: '',
      Title: '',
      Content: '',
    };
    const CurrentDetail = [...content.CurrentDetail, addData];
    setContent({ ...content, CurrentDetail });
  };

  const addChildLevel = (index: number) => {
    const ChildDetail = content.ChildDetail;
    const addData = {
      ID: guid(),
      ConverPic: '',
      MediaUrl: '',
      Title: '',
      Content: '',
    };
    ChildDetail[index].ManualInfo.push(addData);
    setContent({ ...content, ChildDetail });
  };

  const uploadVideo = (e) => {
    const file = e.target.files[0];
    if (file.size > 1024 * 1024 * 1024) {
      Message.warning('上传大小不能超过1G');
      return;
    }
    setVideoIsUploading(true);
    Message.success('上传中，请稍后');

    aliOss
      .uploadImage(file, 'educatoinHelpVideo', 'mp4')
      .then((res) => {
        setVideoIsUploading(false);
        if (currentUplevel === 1) {
          const CurrentDetail = content.CurrentDetail;
          CurrentDetail[currentUpIndex1].MediaUrl = res;
          setContent({ ...content, CurrentDetail });
        } else {
          const ChildDetail = content.ChildDetail;
          ChildDetail[currentUpIndex1].ManualInfo[currentUpIndex2].MediaUrl =
            res;
          setContent({ ...content, ChildDetail });
        }

        Message.success('上传成功');
      })
      .catch((err) => {
        setVideoIsUploading(false);
        console.error(`Common upload ${file.name} failed === `, err);
        Message.error('上传失败');
      });

    const idName =
      currentUplevel === 1
        ? `addVideo-${currentUplevel}-${currentUpIndex1}`
        : `addVideo-${currentUplevel}-${currentUpIndex1}-${currentUpIndex2}`;

    (document.getElementById(idName) as any).value = '';
  };
  const handleVideo = (level: number, index1: number, index2 = 0) => {
    if (videoIsUploading) {
      Message.warning('存在正在上传的视频，请稍后');
      return;
    }
    setCurrentUplevel(level);
    setCurrentUpIndex1(index1);
    if (level === 2) {
      setCurrentUpIndex2(index2);
    }
    const addVideo =
      level === 1
        ? document.getElementById(`addVideo-${level}-${index1}`)
        : document.getElementById(`addVideo-${level}-${index1}-${index2}`);
    addVideo.click();
  };

  const uploadImg = async (e) => {
    const file = e.target.files[0];
    const res = await aliOss.uploadImage(file, 'educatoinHelpImg');
    if (currentUplevel === 1) {
      const CurrentDetail = content.CurrentDetail;
      CurrentDetail[currentUpIndex1].ConverPic = res;
      setContent({ ...content, CurrentDetail });
    } else {
      const ChildDetail = content.ChildDetail;
      ChildDetail[currentUpIndex1].ManualInfo[currentUpIndex2].ConverPic = res;
      setContent({ ...content, ChildDetail });
    }
    (document.getElementById('addPic') as any).value = '';
  };

  const handleImg = (level: number, index1: number, index2 = 0) => {
    setCurrentUplevel(level);
    setCurrentUpIndex1(index1);
    if (level === 2) {
      setCurrentUpIndex2(index2);
    }

    const addPic = document.getElementById('addPic');
    addPic.click();
  };

  const titleChange = (
    title: string,
    level: number,
    index1: number,
    index2 = 0
  ) => {
    if (level === 1) {
      const CurrentDetail = content.CurrentDetail;
      CurrentDetail[index1].Title = title;
      setContent({ ...content, CurrentDetail });
    } else {
      const ChildDetail = content.ChildDetail;
      ChildDetail[index1].ManualInfo[index2].Title = title;
      setContent({ ...content, ChildDetail });
    }
  };

  const delFirstLevel = (index: number) => {
    const CurrentDetail = content.CurrentDetail;
    CurrentDetail.splice(index, 1);
    setContent({ ...content, CurrentDetail });
  };

  const delChildLevel = (index1: number, index2: number) => {
    const ChildDetail = content.ChildDetail;
    ChildDetail[index1].ManualInfo.splice(index2, 1);
    setContent({ ...content, ChildDetail });
  };

  const deleteVideo = (level: number, index1: number, index2 = 0) => {
    if (level === 1) {
      const CurrentDetail = content.CurrentDetail;
      CurrentDetail[index1].MediaUrl = '';
      setContent({ ...content, CurrentDetail });
    } else {
      const ChildDetail = content.ChildDetail;
      ChildDetail[index1].ManualInfo[index2].MediaUrl = '';
      setContent({ ...content, ChildDetail });
    }
  };

  const playVideo = (url: string) => {
    window.open(url);
  };

  const onSave = async () => {
    const res: any = await configureHelpManual(content);
    if (res.StatusCode === 200) {
      Message.success(res.Message);
      history.back();
    } else {
      Message.error(res.Message);
    }
  };

  return (
    <div>
      {content && (
        <div>
          <Card>
            <Title heading={6}>类型：{typeLabel}</Title>
            <Title heading={6}>一级分类：{content.Name}</Title>
            <Button type="outline" onClick={addFirstLevel}>
              新增内容
            </Button>

            <ReactSortable
              list={content.CurrentDetail}
              handle=".drag-handle"
              setList={(newState) =>
                setContent({ ...content, CurrentDetail: newState })
              }
              style={{ display: 'flex', flexWrap: 'wrap', marginTop: 20 }}
            >
              {content.CurrentDetail.map((first, index: number) => {
                return (
                  <Card
                    bordered={true}
                    style={{
                      width: 370,
                      marginRight: 20,
                      marginBottom: 20,
                      position: 'relative',
                    }}
                  >
                    <Popconfirm
                      focusLock
                      title="提示"
                      content="是否确认删除？"
                      onOk={() => {
                        delFirstLevel(index);
                      }}
                    >
                      <Button
                        shape="circle"
                        icon={<IconDelete />}
                        className={styles['delete-icon']}
                      />
                    </Popconfirm>

                    <IconDragDot
                      className={`${styles['drag-handle']} drag-handle`}
                    />

                    <Row className="grid-demo" style={{ marginBottom: 16 }}>
                      <Col span={12}>
                        <Title heading={6}>视频</Title>
                        <input
                          type="file"
                          id={`addVideo-1-${index}`}
                          onChange={uploadVideo}
                          style={{ display: 'none' }}
                          accept=".mp4"
                        />

                        {!first.MediaUrl && (
                          <div
                            onClick={() => handleVideo(1, index)}
                            className={styles['upload-box']}
                          >
                            <IconPlus style={{ fontSize: 30 }} />
                            <span>点击上传视频</span>
                          </div>
                        )}

                        {first.MediaUrl && (
                          <div className={styles['upload-img-box']}>
                            <video
                              id={`video-1-${index}`}
                              className={styles['upload-img']}
                              width="120"
                              height="120"
                              src={first.MediaUrl}
                            ></video>
                            <Button
                              shape="circle"
                              size="mini"
                              icon={<IconClose />}
                              className={styles['upload-img-del']}
                              onClick={() => deleteVideo(1, index)}
                            />

                            <Button
                              shape="circle"
                              icon={<IconPlayArrow />}
                              size="large"
                              className={styles['video-play-icon']}
                              onClick={() => playVideo(first.MediaUrl)}
                            />
                          </div>
                        )}
                      </Col>
                      <Col span={12}>
                        <Title heading={6}>视频封面</Title>
                        <input
                          type="file"
                          id="addPic"
                          onChange={uploadImg}
                          style={{ display: 'none' }}
                          accept="image/gif, image/jpeg ,image/png"
                        />

                        {!first.ConverPic && (
                          <div
                            className={styles['upload-box']}
                            onClick={() => handleImg(1, index)}
                          >
                            <IconPlus style={{ fontSize: 30 }} />
                            <span>点击上传图片</span>
                          </div>
                        )}

                        {first.ConverPic && (
                          <img
                            onClick={() => handleImg(1, index)}
                            className={styles['upload-img']}
                            src={first.ConverPic}
                            width={120}
                            height={120}
                          ></img>
                        )}
                      </Col>
                    </Row>
                    <Row className="grid-demo" style={{ marginBottom: 16 }}>
                      <Col span={24}>
                        <div>
                          <Title heading={6}>视频标题</Title>
                          <Input
                            allowClear
                            value={first.Title}
                            onChange={(value) => titleChange(value, 1, index)}
                          />
                        </div>
                      </Col>
                    </Row>
                    <Row className="grid-demo">
                      <Col span={24} style={{ height: 20 }}>
                        <Title heading={6}>序号：{index + 1}</Title>
                      </Col>
                    </Row>
                  </Card>
                );
              })}
            </ReactSortable>

            {content.ChildDetail.map((child, index: number) => {
              return (
                <div style={{ marginBottom: 20 }}>
                  <Title heading={6}>
                    二级分类{index + 1}：{child.Name}
                  </Title>
                  <Button type="outline" onClick={() => addChildLevel(index)}>
                    新增内容
                  </Button>

                  <ReactSortable
                    list={content.ChildDetail[index].ManualInfo}
                    handle=".drag-handle"
                    setList={(newState) => {
                      const ChildDetail = content.ChildDetail;
                      ChildDetail[index].ManualInfo = newState;
                      setContent({ ...content, ChildDetail });
                    }}
                    style={{ display: 'flex', flexWrap: 'wrap', marginTop: 20 }}
                  >
                    {content.ChildDetail[index].ManualInfo.map(
                      (info, index2: number) => {
                        return (
                          <Card
                            bordered={true}
                            style={{
                              width: 370,
                              marginRight: 20,
                              marginBottom: 20,
                            }}
                          >
                            <Popconfirm
                              focusLock
                              title="提示"
                              content="是否确认删除？"
                              onOk={() => {
                                delChildLevel(index, index2);
                              }}
                            >
                              <Button
                                shape="circle"
                                icon={<IconDelete />}
                                className={styles['delete-icon']}
                              />
                            </Popconfirm>

                            <IconDragDot
                              className={`${styles['drag-handle']} drag-handle`}
                            />
                            <Row
                              className="grid-demo"
                              style={{ marginBottom: 16 }}
                            >
                              <Col span={12}>
                                <Title heading={6}>视频</Title>
                                <input
                                  type="file"
                                  id={`addVideo-2-${index}-${index2}`}
                                  onChange={uploadVideo}
                                  style={{ display: 'none' }}
                                  accept=".mp4"
                                />

                                {!info.MediaUrl && (
                                  <div
                                    onClick={() =>
                                      handleVideo(2, index, index2)
                                    }
                                    className={styles['upload-box']}
                                  >
                                    <IconPlus style={{ fontSize: 30 }} />
                                    <span>点击上传视频</span>
                                  </div>
                                )}

                                {info.MediaUrl && (
                                  <div className={styles['upload-img-box']}>
                                    <video
                                      id={`video-1-${index}-${index2}`}
                                      className={styles['upload-img']}
                                      width="120"
                                      height="120"
                                      src={info.MediaUrl}
                                    ></video>
                                    <Button
                                      shape="circle"
                                      size="mini"
                                      icon={<IconClose />}
                                      className={styles['upload-img-del']}
                                      onClick={() =>
                                        deleteVideo(2, index, index2)
                                      }
                                    />

                                    <Button
                                      shape="circle"
                                      icon={<IconPlayArrow />}
                                      size="large"
                                      className={styles['video-play-icon']}
                                      onClick={() => playVideo(info.MediaUrl)}
                                    />
                                  </div>
                                )}
                              </Col>
                              <Col span={12}>
                                <Title heading={6}>视频封面</Title>
                                <input
                                  type="file"
                                  id="addPic"
                                  onChange={uploadImg}
                                  style={{ display: 'none' }}
                                  accept="image/gif, image/jpeg ,image/png"
                                />

                                {!info.ConverPic && (
                                  <div
                                    className={styles['upload-box']}
                                    onClick={() => handleImg(2, index, index2)}
                                  >
                                    <IconPlus style={{ fontSize: 30 }} />
                                    <span>点击上传图片</span>
                                  </div>
                                )}

                                {info.ConverPic && (
                                  <img
                                    onClick={() => handleImg(2, index, index2)}
                                    className={styles['upload-img']}
                                    src={info.ConverPic}
                                    width={120}
                                    height={120}
                                  ></img>
                                )}
                              </Col>
                            </Row>
                            <Row
                              className="grid-demo"
                              style={{ marginBottom: 16 }}
                            >
                              <Col span={24}>
                                <div>
                                  <Title heading={6}>视频标题</Title>
                                  <Input
                                    allowClear
                                    value={info.Title}
                                    onChange={(value) =>
                                      titleChange(value, 2, index, index2)
                                    }
                                  />
                                </div>
                              </Col>
                            </Row>
                            <Row className="grid-demo">
                              <Col span={24} style={{ height: 20 }}>
                                <Title heading={6}>序号：{index2 + 1}</Title>
                              </Col>
                            </Row>
                          </Card>
                        );
                      }
                    )}
                  </ReactSortable>
                </div>
              );
            })}
          </Card>

          <div className={styles.actions}>
            <Space>
              <Button
                size="large"
                onClick={() => {
                  history.back();
                }}
              >
                取消
              </Button>
              <Button type="primary" size="large" onClick={onSave}>
                保存
              </Button>
            </Space>
          </div>
        </div>
      )}
    </div>
  );
}
export default manualsContent;
